#!/bin/bash

# 参数校验
  if [ $# -eq 0 ]; then
  echo "错误：未指定配置文件路径！"
echo "用法: $0 <配置文件路径>"
  exit 1
  fi
  
  CONFIG_FILE=$1
  
  # 检查配置文件是否存在
  if [ ! -f "$CONFIG_FILE" ]; then
  echo "错误：配置文件 $CONFIG_FILE 不存在！"
  exit 1
  fi
  
  # 从 YAML 中解析配置（需安装 yq）
  JOB_NAME=$(yq eval '.job.name' $CONFIG_FILE)
  MAIN_CLASS=$(yq eval '.job.jar.main_class' $CONFIG_FILE)
  CHECKPOINT_DIR=$(yq eval '.job.checkpoint.dir' $CONFIG_FILE)
  FLINK_HOME=$(yq eval '.job.flink.home' $CONFIG_FILE)
  JAR_PATH=$(yq eval '.job.jar.path' $CONFIG_FILE)
  FLINK_REST=$(yq eval '.job.flink.rest' $CONFIG_FILE)

# 1. 停止同名任务
echo "正在停止同名任务: $JOB_NAME..."
  JOB_ID=$($FLINK_HOME/bin/flink list -r | grep "$JOB_NAME" | awk '{print $4}')
  if [ -n "$JOB_ID" ]; then
  $FLINK_HOME/bin/flink cancel $JOB_ID
echo "已停止任务 ID: $JOB_ID"
  else
  echo "未找到运行中的任务。"
  fi
  
  # 2. 查找最新 Checkpoint
  LATEST_CHK=$(
  ls -td $CHECKPOINT_DIR/chk-* 2>/dev/null \
  | head -1
  )
  
  # 3. 清理旧 Checkpoint（保留最近 N 次）
  RETAIN_COUNT=$(yq eval '.job.checkpoint.retain' $CONFIG_FILE)
  if [ -n "$RETAIN_COUNT" ]; then
  echo "清理旧 Checkpoint（保留最近 $RETAIN_COUNT 次）..."
  find $CHECKPOINT_DIR -name "chk-*" -type d \
  | sort -r \
  | tail -n +$(($RETAIN_COUNT + 1)) \
  | xargs rm -rf
  fi
  
  # 4. 根据 Checkpoint 状态提交任务
  if [ -n "$LATEST_CHK" ]; then
  echo "检测到 Checkpoint，从 $LATEST_CHK 恢复任务..."
  $FLINK_HOME/bin/flink run \
  -d \
  -s file://$LATEST_CHK \
  -c $MAIN_CLASS \
  $JAR_PATH
  else
  echo "未找到 Checkpoint，启动新任务..."
  $FLINK_HOME/bin/flink run \
  -d \
  -c $MAIN_CLASS \
  $JAR_PATH
  fi
  
  # 5. 验证任务状态
  echo "等待任务启动..."
  sleep 5
  JOB_ID=$($FLINK_HOME/bin/flink list -r | grep "$JOB_NAME" | awk '{print $4}')
  if [ -n "$JOB_ID" ]; then
echo "任务已启动，ID: $JOB_ID"
echo "监控地址: $FLINK_REST/#/jobs/$JOB_ID"
  else
  echo "任务启动失败！请检查日志。"
  exit 1
  fi